package router

import (
	"bigStudy/util"
	"fmt"
	"io"
	"net/http"
	"os"

	"github.com/gin-gonic/gin"
)

func init() {
	// 日志输出到文件
	logFile, err := os.OpenFile("log.log", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644)
	if err != nil {
		logFile, _ = os.Create("log.log")
		return
	}
	gin.DisableConsoleColor() //保存到文件不需要颜色
	gin.DefaultWriter = io.MultiWriter(logFile)
	gin.SetMode(gin.ReleaseMode)
}

// Router ..
func Router() {
	r := gin.Default()
	r.StaticFS("/img", http.Dir("./cache"))
	r.StaticFile("/favicon.ico", "./resources/favicon.ico")
	r.LoadHTMLGlob("pages/*")

	//设定请求url不存在的返回值
	r.NoRoute(NoResponse)

	r.GET("/index", homePage)

	r.GET("index/:class", classPage)

	r.GET("submit/:class", submitEndpoint)

	r.GET("/read/:class", readEndpoint)

	r.POST("/upload/:class", uploadEndpoint)

	r.GET("/downfile", downEndpoint)

	r.GET("/createclass", func(c *gin.Context) {
		class := c.Query("classNum")
		isDir := util.ClassPageExists(class)

		if isDir {
			// 指定重定向的URL
			c.Request.URL.Path = "/index/" + class
			r.HandleContext(c)
		} else if len(class) != 4 {
			c.HTML(http.StatusOK, "hint.html", gin.H{
				"msg": "创建失败,输入正确的班号",
			})
		} else {
			imgDirPath := fmt.Sprintf("./img/%s", class)
			exportDirPath := fmt.Sprintf("./export/%s", class)
			cacheDirPath := fmt.Sprintf("./cache/%s", class)
			// 创建图片路径
			err1 := os.Mkdir(imgDirPath, os.ModePerm)
			err2 := os.Mkdir(exportDirPath, os.ModePerm)
			err3 := os.Mkdir(cacheDirPath, os.ModePerm)
			if err1 == nil && err2 == nil && err3 == nil {
				// 指定重定向的URL
				c.Request.URL.Path = "/index/" + class
				r.HandleContext(c)
			} else {
				c.HTML(http.StatusOK, "hint.html", gin.H{
					"msg": "创建失败,输入正确的班号",
				})
			}
		}
	})

	r.Run(":80")
}
